/* global chrome */
import { get, post } from "@/http/http";

// 监听来自background的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  console.log(sender, sendResponse, 'sender,sendResponse');

  if (request.action === "handleInterceptedRequest") {
    console.log(request, "requestppppppppppp");

    handleInterceptedRequest(request.data);
  }
});

// 处理拦截后的请求
async function handleInterceptedRequest(data) {
  console.log(data, 'responsewwwwwwwwww  data');

  try {
    // 发送到新接口
    const response = await get("/data/basic/trading", data);
    console.log(response, "responsewwwwwwwwww");
  } catch (error) {
    console.error("处理拦截请求时出错:", error);
  }
}





// 测试
// chrome.runtime.sendMessage(
//   {
//     action: "interceptRequest",
//     url: "https://www.gate.io/apiw/v2/unified/futures/usdt/contracts",
//   },
//   (response) => {
//     if (chrome.runtime.lastError) {
//       console.error("消息发送失败：", chrome.runtime.lastError.message);
//     } else {
//       console.log("收到响应：", response);
//     }
//   }
// );

export function clickBuyOrSellBtn() {
  const btn = document.querySelector(".trading_sub > .mantine-1v71nuo");
  console.log(btn, "btn");
  if (btn) {
    const originalHandler = btn.onclick;
    if (originalHandler) {
      btn.onclick = null;
    }

    btn.addEventListener("click", async (event) => {
      console.log("买入按钮被点击");

      event.preventDefault();

      console.log("执行自定义逻辑");
      // chrome.runtime.sendMessage(
      //   {
      //     action: "interceptRequest",
      //     url: "https://www.gate.io/apiw/v2/unified/futures/usdt/contracts",
      //   },
      //   (response) => {
      //     if (chrome.runtime.lastError) {
      //       console.error("消息发送失败：", chrome.runtime.lastError.message);
      //     } else {
      //       console.log("收到响应：", response);
      //     }
      //   }
      // );
      getAllTradeValue();
    });
  } else {
    console.log("未找到买入按钮");
  }
}

function getAllTradeValue() {
  const sliderInput = document.querySelector(
    ".trade-slider-container > .mantine-1dpcsaw > input"
  );
  if (sliderInput) {
    console.log(sliderInput, "sliderInput");
    const sliderValue = sliderInput.value;
    console.log(sliderValue, "sliderValue000000");
    sliderInput.value = 0.5;
    const event = new Event("input", { bubbles: true });
    sliderInput.dispatchEvent(event);
    console.log(sliderInput.value, "sliderInput.value1111111");
    console.log(sliderInput, "sliderInput2222222");
  } else {
    console.log("未找到.trade-slider-container > .mantine-1dpcsaw > input节点");
  }
  const params = {};
  //   setInterval(() => {
  const profitAndStopLoss = takeProfitStopLoss();
  const advanceValue = advancedOptions();
  console.log(profitAndStopLoss, "profitAndStopLoss");
  console.log(advanceValue, "advanceValue");
  const tradeInput = document.querySelectorAll(
    ".mantine-1i52ecs > .mantine-ysl0gg"
  );
  if (tradeInput) {
    params.priceValue = tradeInput[0].value;
    params.numValue = tradeInput[1].value;
    params.operateAsset = tradeInput[2].value;
    if (profitAndStopLoss) {
      params.profitValue = tradeInput[3].value;
      params.stopLossValue = tradeInput[4].value;
      if (advanceValue.icebergValue) {
        params.advanceValue = tradeInput[5].value;
      }
    } else {
      if (advanceValue.icebergValue) {
        params.advanceValue = tradeInput[3].value;
      }
    }
  }
  params.id = JSON.parse(localStorage.getItem('userInfo')).id
  const buySellBtn = document.querySelector(".mantine-5wozre > .kNqabE");
  console.log(buySellBtn, "buySellBtn");
  if (buySellBtn) {
    if (buySellBtn.innerText == "买入") {
      params.operateType = 'in'
    } else {
      params.operateType = 'out'
    }
  } else {
    console.log("未找到.mantine-5wozre > .kNqabE买入按钮节点");
  }
  console.log(params, "params");
  post("/user/update", params)
    .then((res) => {
      console.log("transaction post Response111222555777888:", res);
      if (res.code == 200) {
        get('/user/info', { email: localStorage.getItem('username') }).then(res => {
          localStorage.setItem('userInfo', res.data)
        })
      }
    })
    .catch((err) => {
      console.error("spotCurrentCommission post Error fetching data:", err);
    });
  //   }, 5000);
}

function takeProfitStopLoss() {
  const takeProfitAndStopLoss = document.querySelector(
    ".mantine-hpmcve > .mantine-um7x36 > .mantine-xsvmgd > .mantine-11lhrkx > input"
  );
  let profitAndStopLoss = false;
  console.log(takeProfitAndStopLoss, "takeProfitAndStopLoss");
  if (takeProfitAndStopLoss) {
    if (takeProfitAndStopLoss.checked) {
      profitAndStopLoss = true;
    }
  }
  return profitAndStopLoss;
  //   if (takeProfitAndStopLoss) {
  //     const trueProfitLoss = takeProfitAndStopLoss.querySelector("span");
  //     console.log(trueProfitLoss, "trueProfitLoss");
  //     const tradeInput = document.querySelectorAll(
  //       ".mantine-1i52ecs > .mantine-ysl0gg"
  //     );
  //     /**
  //      * tradeInput[0] 是价格输入框
  //      * tradeInput[1] 是数量输入框
  //      * tradeInput[2] 是交易额输入框
  //      * tradeInput[3] 是止盈输入框
  //      * tradeInput[4] 是止损输入框
  //      */

  //     if (trueProfitLoss && tradeInput) {
  //       // 五个输入框
  //       console.log(tradeInput, "allInputtttt");
  //       if (tradeInput.length < 5) {
  //         console.log(".mantine-1i52ecs > .mantine-ysl0gg 查找输入框不足");
  //       }
  //     }
  //     if (!trueProfitLoss && tradeInput) {
  //       // 三个输入框
  //       console.log("未找到止盈止损输入框");
  //       if (tradeInput.length < 3) {
  //         console.log(".mantine-1i52ecs > .mantine-ysl0gg 查找输入框不足");
  //       }
  //     }
  //   } else {
  //     console.log("未找到.mantine-hpmcve节点");
  //   }
}

function advancedOptions() {
  const element = document.querySelector(
    '.mantine-17wb7nx span[style*="transform"]'
  ); // 查找包含 transform 样式的 span 元素
  console.log(element, "advancedOptions");
  const advanceValue = {};
  if (element) {
    const rotateValue = element.style.transform
      .split("rotate(")[1]
      .split("deg)")[0];
    console.log(rotateValue, "rotateValue");
    if (rotateValue == "180") {
      const checkboxGroup = document.querySelectorAll(
        ".mantine-muwcf3 > .mantine-xsvmgd > .mantine-11lhrkx > .mantine-14u1gnw"
      );
      console.log(checkboxGroup, "checkboxGroup");
      if (checkboxGroup) {
        if (checkboxGroup[0].checked) {
          advanceValue.postValue = true;
        }
        if (checkboxGroup[1].checked) {
          advanceValue.iocValue = true;
        }
        if (checkboxGroup[2].checked) {
          advanceValue.icebergValue = true;
        }
      }
    }
    return advanceValue;
  } else {
    console.log("未找到包含 transform 样式的元素");
  }
}
